<?
/**
*   version 05.03.2007
*   + extented XML error messaging 
**/

define('RBNS_INCLUDE_COMMENT_START','rbns_start_include');
define('RBNS_INCLUDE_COMMENT_FINISH','rbns_finish_include'); 

function returnIncludeStack($linesArray, $fromLine){
	$brackets=0;
	$result=array();
    $firstline=0; 
	for($i=$fromLine; $i>0; $i--){
		
		if(($pos=strpos($linesArray[$i],RBNS_INCLUDE_COMMENT_START))!==false){
			if($brackets<=0){
				$result[]=substr($linesArray[$i],$pos+strlen(RBNS_INCLUDE_COMMENT_START));
				if(empty($firstline)) $firstline=$i;
			}else{
				$brackets--;
			};
		}elseif(strpos($linesArray[$i],RBNS_INCLUDE_COMMENT_FINISH)!==false){
			$brackets++;
		};
	}
	return " check line ".($fromLine-$firstline)." there : ".implode('<br>', $result);
}


function _getRBNSInclude($ar){


	$fn=trim($ar[1]);
	if(empty($fn)) return "";

	if($fn[0]!='/') $fn="/".$fn;
	$fn="$_SERVER[DOCUMENT_ROOT]".$fn;
	$data="";
	if(file_exists($fn))
	{

		if (!($fp = @fopen($fn, "r")))    return false;
		$data = fread($fp, filesize($fn));
		fclose($fp);
	} else  die("<font color='red'>Not Found $fn </font>");

	return "\n<!--".RBNS_INCLUDE_COMMENT_START."  RBNS:include file={$fn} -->\n".$data."\n<!--".RBNS_INCLUDE_COMMENT_FINISH."  RBNS:include file={$fn} -->\n";

}

function _getRBNSVar($ar){
	global $__RBNSVarDef;


	return $__RBNSVarDef[$ar[1]];

}

function _getRBNSVarDef($ar){
	global $__RBNSVarDef;
    
	$__RBNSVarDef[$ar[1]]="\n<!--".RBNS_INCLUDE_COMMENT_START."  RBNS:includeVarDef var={$ar[1]} -->\n".$ar[2]."\n<!--".RBNS_INCLUDE_COMMENT_FINISH."  RBNS:include file={$fn} -->\n";
	// this variable show is content present
	$__RBNSVarDef[$ar[1]."_content"] = trim($ar[2])!=''; 
}



function _memRBNSHeadDef($ar){
	global $__frameHeadDef;

	$__frameHeadDef[$ar[1]]=$ar[2];
}

function _memRBNSHeadSet($ar){
	global $__frameHeadDef;
	if(isset( $__frameHeadDef[$ar[1]])){	return $__frameHeadDef[$ar[1]];
	}else die("<font color='red'>Found ".htmlspecialchars($ar[0])." without pre-definition in ".htmlspecialchars("<RBNS:frameFootDefinition name='$ar[1]'>"));
}

function _memRBNSFootDef($ar){
	global $__frameFootDef;

	$__frameFootDef[$ar[1]]=$ar[2];
}

function _memRBNSFootSet($ar){
	global $__frameFootDef;
	if(isset( $__frameFootDef[$ar[1]])){	return $__frameFootDef[$ar[1]];
	}else die("<font color='red'>Found ".htmlspecialchars($ar[0])." without pre-definition in ".htmlspecialchars("<RBNS:frameFootDefinition name='$ar[1]'>"));
}


function _slashed($ar){
	print_r($ar);
}


class RBNS_parser extends RBNS{


	var $parse_results=array();
	var $parse_result;
	var $vparser;//object of varparse

	var $iFB=0; // counter of forms embeding
	var $FormsData=array();
	var $ifpresent=array();
	var $defvarout;
	
	function RBNS_parser($file='') {

		parent::__construct();
		$this->parser = xml_parser_create();
		

		xml_set_object($this->parser,$this);
		xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 1);
		xml_set_element_handler($this->parser, "startElement", "endElement");
		xml_set_character_data_handler($this->parser, "characterData");
		xml_set_default_handler($this->parser, "defaultHandler");


		$this->vparser=new varparse(false);

		$this->openLB();
		if(!empty($file)) $this->getDataFromFile($file);


	}








	function getDataFromFile($file){

		if (!($fp = @fopen($file, "r"))) {
			return false;
		}

		$this->data = fread($fp, filesize($file));

		fclose($fp);
		return true;
	}





	function parse(){

		if(empty($this->data) )
		{
			die("parse error: empty data");

		};
		// include externalfile
		//pseudo-function {?RBNS_include(filename)?}


		//<RBNS:include file='/filename' />
		$alpha='/\{\?RBNS_include\([\'\"]([a-z0-9.\/_]+)[\'\"]\)\?\}/i';
		$beta='/\<RBNS:include +file=[\'\"]([a-z0-9.\/_]+)[\'\"] +\/>/i';
		$gamma='/\<RBNS:include +var=[\'\"]([a-z0-9.\/_]+)[\'\"] +\/>/i';
		$tetta='/\<RBNS:includeVarDef +name=[\'\"]([\w\d_]+)[\'\"] *>(.*)<\/RBNS:includeVarDef>/misU';
		while(preg_match($alpha,$this->data)||preg_match($beta,$this->data)||preg_match($gamma,$this->data)||preg_match($tetta,$this->data))
		{
			$this->data=preg_replace_callback ($tetta, "_getRBNSVarDef", $this->data);
			$this->data=preg_replace_callback ($alpha, "_getRBNSInclude", $this->data);
			$this->data=preg_replace_callback ($beta, "_getRBNSInclude", $this->data);
			$this->data=preg_replace_callback ($gamma, "_getRBNSVar", $this->data);
		}
		// echo htmlspecialchars($this->data );
		//RBNS:frame preparation
		//frameHead definition
		$pttr1='/\<RBNS:frameHeadDefinition +name=[\'\"]([\w\d]+)[\'\"] *>(.*)<\/RBNS:frameHeadDefinition>/misU';
		// frameFoot definition
		$pttr2='/\<RBNS:frameFootDefinition +name=[\'\"]([\w\d]+)[\'\"] *>(.*)<\/RBNS:frameFootDefinition>/misU';
		//frameHead replace
		$pttr3='/\<RBNS:frameHead +name=[\'\"]([\w\d]+)[\'\"] *\/>/miU';

		//frameFoot replace
		$pttr4='/\<RBNS:frameFoot +name=[\'\"]([\w\d]+)[\'\"] *\/>/miU';
		// use while for catch embedded frame
		while(preg_match($pttr1,$this->data)||preg_match($pttr2,$this->data)||preg_match($pttr3,$this->data)||preg_match($pttr4,$this->data)){ ;

		$this->data=preg_replace_callback ($pttr1, "_memRBNSHeadDef", $this->data);
		$this->data=preg_replace_callback ($pttr2, "_memRBNSFootDef", $this->data);
		$this->data=preg_replace_callback ($pttr3, "_memRBNSHeadSet", $this->data);
		$this->data=preg_replace_callback ($pttr4, "_memRBNSFootSet", $this->data);
		}














		// echo $this->data;
		//prepare data -> HTML to XML data
		$this->data=preg_replace('/(<RBNS:)(.+)(>)/Ui','OpenRBNSTAG\\2CloseRBNSTAG',$this->data);
		$this->data=preg_replace('/(<\/RBNS:)([^>]+)(>)/Ui','OpenRBNSTooTAG\\2CloseRBNSTAG',$this->data);
		$this->data=htmlspecialchars ($this->data,ENT_NOQUOTES);
		$this->data = str_replace ('OpenRBNSTAG', '<RBNS:', $this->data);
		$this->data = str_replace ('CloseRBNSTAG', '>', $this->data);
		$this->data = str_replace ('OpenRBNSTooTAG', '</RBNS:', $this->data);
		if(!ereg('^<RBNS:dataportion>.+</RBNS:dataportion>$',$this->data)) $this->data="<RBNS:dataportion>$this->data</RBNS:dataportion>";
		
		if(!preg_match('/<\?xml /',$this->data)){
			
			if(defined('RBNS_XML_ENCODE')){
				$this->data="<?xml version='1.0' encoding='".RBNS_XML_ENCODE."' ?>\n".$this->data;
			};
				
		}
		

		if (!xml_parse($this->parser, $this->data))
		{
			//error!
			$fname="$_SERVER[DOCUMENT_ROOT]/temp/template_translate_result.htm";
			if(!$fn=fopen($fname,'w'))  die("File $fname is not exists!");
			fwrite($fn,$this->data);
			fclose($fn);
			$ln=xml_get_current_line_number($this->parser);
			$errodata=preg_split('/^/mi',$this->data);
			//var_export($errodata);
			
			die(sprintf("XML error: %s at(about) line %d look at %s for detail.<br>==> %s<br><br>stack ==><br>%s",
						xml_error_string(xml_get_error_code($this->parser)),
						$ln,
						$fname,
						htmlspecialchars($errodata[$ln]),
						returnIncludeStack($errodata,$ln)
				));

		}
		$this->parse_result=$this->varparse($this->parse_result,$this->defvarout);

		$this->parse_result=preg_replace('/<\?xml(.*)\?>/miU','____xmlOpTag\\1____xmlCloseTag',$this->parse_result);

		$this->parse_result=preg_replace('/\?>\s*<\?php/mi','',$this->parse_result);


		$this->parse_result=preg_replace('/<\?php.*____xmlOpTag(.*)____xmlCloseTag.*\?>/miU','echo "<?xml\\1?>";',$this->parse_result);

		$this->parse_result=preg_replace('/____xmlOpTag(.*)____xmlCloseTag/miU','<?php echo "<?xml\\1?>";?>',$this->parse_result);
		
		if(defined('RBNS_XML_ENCODE') )
		{
			if( ($this->parse_result=iconv('UTF-8',RBNS_XML_ENCODE,$this->parse_result))===false){
				
				$this->errorstream(" ICONV library error. Check iconv settings. Try change or cancel RBNS_XML_ENCODE constant ");
			}
		};
	}


	function toArrayVar($arrayName,$vars){
		if(strpos($vars,"[")!==false){
			$s1=strtok($vars,"[");
			$s2=strstr($vars,"[");
			if($s2=='[]') return $arrayName."[".$s1."]";
			else return $arrayName."[".$s1."]".$s2;
		}
		else
		{
			return $arrayName."[".$vars."]";
		};
	}



	function trustedFile($file) {
		// only trust local files owned by ourselves
		if (!eregi("^([a-z]+)://", $file)
		&& fileowner($file) == getmyuid()) {
			return true;
		}
		return false;
	}

	var $alone_flag=false;
	
	//  flaf of tag which be alone - mean without something in it

	function setAloneFlag($name){

		if($this->alone_flag)// flag was setted so error
		die(sprintf("parser error at line %d: Surrounding tag of %s must be empty \n",
		xml_get_current_line_number($this->parser),$name)
		);

		$this->alone_flag=true;
	}


	function out($s){

		if(!is_array($this->parse_results)) openLB();

		$this->parse_result.=$s;
	}


	function replaceInResult($search,$replace){


		for($i=1;$i<=$this->iLB;$i++)
		$this->parse_results[$i]=str_replace($search,$replace,$this->parse_results[$i]); // search in array!
	}

	var $iLB=0;//counter of open/close logical blocks 

	// open block
	function openLB(){
		$this->iLB++;
		$this->parse_result=&$this->parse_results[$this->iLB];

	}


	function closeLB(){

		$this->iLB--;
		if($this->iLB<=0)  die(sprintf("parser error at line %d: Block counter set zero!  \n",
		xml_get_current_line_number($this->parser))
		);

		$this->parse_results[$this->iLB].=$this->parse_result;
		$this->parse_result='';
		$this->parse_result=&$this->parse_results[$this->iLB];

	}

	function checkIsAlonePresent($parser,$name){

		if($this->alone_flag)
		die(sprintf("parser error at line %d: Surrounding tag of %s must be empty \n",
		xml_get_current_line_number($parser),$name)
		);

	}


	function clearAloneFlag(){

		$this->alone_flag=false;
	}



	function prepareParam($str,$wrnstr,$type='',$vpF=1){
		if(empty($str)) return $str;

		//$str=$this->makeObjectSyntax($str);

		$str=str_replace('&quot;','"',$str);
		$str=$this->varparse($str,$vpF);


		$str=trim($str);
		$en=substr($str,-1);
		if( (!(($str[0]=='"')|($str[0]=="'"))) || (!(($en=='"')|($en=="'")) ) )
		{
			if($type=='str') die(sprintf("RBNS parse error: %s at line  %d\n",
			" attribyte must be string type $wrnstr ",
			xml_get_current_line_number($this->parser)));

		};
		if( $type=='int'){

			$temp = (int) $str;
			$temp = (string) $temp;

			if ($temp<> $str) {
				die(sprintf("RBNS parse error: %s at line  %d\n",
				" attribyte must be integer type $wrnstr ",
				xml_get_current_line_number($this->parser)));
			};
		};
		return $str;

	}


  function getFormErrorName(){
  	
  	return "\$". $this->toArrayVar("_FORM_error_",$this->FormsData[$this->iFB]['NAME']);	
  }


	function startElement($parser, $name, $attribs) {
		global $errorsArray;

		if(substr(strtoupper($name),0,4)=='RBNS')
		{

			switch ($name)
			{
				// show block form RBNS:FETTERS name=''
				// <RBNS:FANTOM name='' />
				case 'RBNS:FANTOM':
					$this->setAloneFlag($name);
                    if(!isset($attribs['NAME']) || empty($attribs['NAME']))
					$this->errorstream('RBNS_FANTOM_MUST_HAVE_NAME_ATTRIB','critical',' at line'.xml_get_current_line_number($parser));
					if(!$this->fantomNames[$attribs['NAME']])
					$this->errorstream('RBNS_FANTOM_MUST_BE_AFTER_RBNS_FETTERS','critical',' at line'.xml_get_current_line_number($parser));
					$out="<?php echo \$RBNS_fantoms[".$attribs['NAME']."];?>";
					$this->out("$out");
					break;
					
					
					// operator brackets.  
					// fetter get all output of its containt and Fantom show will it
					// 
					// <RBNS:FETTERS name=''></RBNS:FETTERS>
				
				case 'RBNS:FETTERS':
			        if(!isset($attribs['NAME']) || empty($attribs['NAME']))
					$this->errorstream('RBNS_FETTERS_MUST_HAVE_NAME_ATTRIB','critical',' at line'.xml_get_current_line_number($parser));
					if($this->shackle)
					$this->errorstream('RBNS_FETTERS_NOTBE_EMBEDDED','critical',' at line'.xml_get_current_line_number($parser));
					$this->shackle=true;
					if($this->fantomNames[$attribs['NAME']]===true)
					$this->errorstream('RBNS_FETTERS_NOTBE_DUPLICATED','critical',' at line'.xml_get_current_line_number($parser));
					$this->fantomNames[$attribs['NAME']]=true;
					$out="<?php ob_start();?>";

					$this->shackleName=$attribs['NAME'];
					$this->out("$out");



					break;
				case 'RBNS:SET':
					//<RBNS:set name='varname' value='val' />
					$this->setAloneFlag($name);
                   if(!isset($attribs['NAME']) || empty($attribs['NAME']))
					$this->errorstream('RBNS_SET_MUST_HAVE_NAME_ATTRIB','critical',' at line'.xml_get_current_line_number($parser));
					$attribs['NAME']=$this->makeObjectSyntax( $attribs['NAME']);
					$attribs['NAME']=$this->prepareParam( $attribs['NAME'],"attribyte  NAME ");
					$attribs['NAME']=trim($attribs['NAME']);
					$value=$this->prepareParam($attribs['VALUE'],"attribyte  PARAM ");

					$out="<?php \$".$attribs['NAME']."=$value; ?>";


					$this->out("$out");

					break;
				case 'RBNS:FUNCTION':
					//<RBNS:function name='varname' param='val' />
					$this->setAloneFlag($name);
					if(!isset($attribs['NAME']) || empty($attribs['NAME']))
					$this->errorstream('RBNS_FUNCTION_MUST_HAVE_NAME_ATTRIB','critical',' at line'.xml_get_current_line_number($parser));
					$name=$attribs['NAME']=$this->makeObjectSyntax( $attribs['NAME']);
					$param = isset($attribs['PARAM'])?$this->prepareParam($attribs['PARAM'],"attribyte  PARAM "):'';
					$value = isset($attribs['VALUE'])?$this->prepareParam($attribs['VALUE'],"attribyte  PARAM "):'';

					$out="<?php $name($param); ?>";

					$this->out("$out");

					break;

				case 'RBNS:COMMENT':
					$out="<?php echo '<!--';/* ?>";
					$this->out("$out");
					break;


				case 'RBNS:OBJECT':

					$this->setAloneFlag($name);

					if(!isset($attribs['NAME']) || empty($attribs['NAME']))
					$this->errorstream('RBNS_OBJECT_MUST_HAVE_NAME_ATTRIB','critical',' at line'.xml_get_current_line_number($parser));

					$nameobject=$this->prepareParam($attribs['NAME'],"attribyte  NAME ");

					if(!isset($attribs['METHOD']) || empty($attribs['METHOD'])) die(sprintf("RBNS parse error: %s at line %d\n",
					$errorsArray[RBNS_OBJECT_MUST_HAVE_METHOD_ATTRIB],
					xml_get_current_line_number($parser)));

					$method      = isset($attribs['METHOD'])    ? $this->prepareParam($attribs['METHOD'],"attribyte  METHOD "):'';
					$param       = isset($attribs['PARAM'])     ? $this->prepareParam($attribs['PARAM'],"attribyte  PARAM "):'';
					$class       = isset($attribs['CLASS'])     ? $this->prepareParam($attribs['CLASS'],"attribyte  CLASS "):'';
					$classparam  = isset($attribs['CLASSPARAM'])? $this->prepareParam($attribs['CLASSPARAM'],"attribyte  CLASSPARAM "):'';
					$version     = isset($attribs['VERSION'])   ? $this->prepareParam($attribs['VERSION'],"attribyte  VERSION "):'';

					$clerr=" die('can\'t init \'$nameobject\' object because class is not defined');";
					if(empty($class)){ $ini=""; }
					else
					{
						if(!empty($attribs['INIT_ONCE']))
						{
							if (empty($classparam)) { $ini=" init_once('$nameobject','$class'); \$$nameobject=&\$_SESSION['$nameobject']; "; }
							else  					{ $ini=" init_once('$nameobject',\"$class($classparam)\"); \$$nameobject=&\$_SESSION['$nameobject'];";};
						}
						else
						$ini="\$$nameobject=new  $class($classparam);";
					};
					if(!empty($version)){
						$version="\$$nameobject"."->setTemplateVersion(\"$version\");";
					}
					$out="<?php
                ".$ini."
                if (!is_object(\$$nameobject))
      	        {
      	       	    if (is_object(\$GLOBALS[$nameobject]))
      	      	    {
      	      	        \$$nameobject=&\$GLOBALS[$nameobject];

      	      	    }
      	      	   else //initialize
      	      	    {
      	      	       ".$clerr."
      	      	    };
      	        };
      	        // run
      	        {
      	      	    ob_start();
      	            $version
      	            \$$nameobject"."->$method($param);
      	            \$RBNS_result=ob_get_contents();
                    ob_end_clean();
                    eval(\"?>\$RBNS_result<?\");
      	        };
            ?>";

					$this->out("$out");
					break;//case 'RBNS:OBJECT'


				case 'RBNS:FOREACH':
					// <RBNS:foreach array='nameofarray' value='setvaluefromarray' [key='setkeyvaluefromarray']>
					//</RBNS:foreach>
					$this->checkIsAlonePresent($parser,$name);
					if(!isset($attribs['ARRAY']) || empty($attribs['ARRAY']))
						$this->errorstream('RBNS_FOREACH_MUST_HAVE_ARRAY_ATTRIB','critical',' at line'.xml_get_current_line_number($parser));
					$array=$this->prepareParam($attribs['ARRAY'],"attribyte  ARRAY ");

					if(!isset($attribs['VALUE']) || empty($attribs['VALUE']))
						$this->errorstream('RBNS_FOREACH_MUST_HAVE_VALUE_ATTRIB','critical',' at line'.xml_get_current_line_number($parser));
					$value=$this->prepareParam($attribs['VALUE'],"attribyte  VALUE ");
					$key=isset($attribs['KEY'])?$this->prepareParam($attribs['KEY'],"attribyte  KEY "):'';
					if(empty($key))
					$out="<?php if(is_array(\$$array)) foreach(\$$array as \$$value){ ?>";
					else
					$out="<?php if(is_array(\$$array)) foreach(\$$array as \$$key=>\$$value){ ?>";

					$this->openLB();
					$this->out($out);


					break;  //<RBNS:foreach>

				case 'RBNS:DATA':
				
					// assoc array getted from data sourde : this->_src() by defaukt
					//
					//<RBNS:data src='nameofsrc' name='name of array' >
					//</RBNS:data>
					$this->checkIsAlonePresent($parser,$name);
					if(!isset($attribs['SRC']) || empty($attribs['SRC'])) $src="\$this->_src()";  else $src=$this->prepareParam($attribs['SRC'],"attribyte  SRC ")."()";
					if(!isset($attribs['NAME']) || empty($attribs['NAME']))
					$this->errorstream('RBNS_DATA_MUST_HAVE_NAME_ATTRIB','critical',' at line'.xml_get_current_line_number($parser));

					$name=$this->prepareParam($attribs['NAME'],"attribyte  NAME ");

					$out="<?php while(\$$name=$src){ \$this->runAspect('DATA','begin',\$$name); ?>";


					$this->openLB();
					$this->out($out);


					break;  //<RBNS:data>





				case 'RBNS:SQLEACH':
					// <RBNS:sqleach table='nameofarray' name='assocarray' [debug=1] [tail='sqltail'][fields='* by default']>
					//</RBNS:sqleach>
					$this->checkIsAlonePresent($parser,$name);
					if(!isset($attribs['TABLE']) || empty($attribs['TABLE']))
						$this->errorstream('RBNS_SQLEACH_MUST_HAVE_TABLE_ATTRIB','critical',' at line'.xml_get_current_line_number($parser));
					$table=$this->prepareParam($attribs['TABLE'],"attribyte  TABLE ");
					if(!isset($attribs['NAME']) || empty($attribs['NAME']))
						$this->errorstream('RBNS_SQLEACH_MUST_HAVE_NAME_ATTRIB','critical',' at line'.xml_get_current_line_number($parser));
					$name=$this->prepareParam($attribs['NAME'],"attribyte  NAME ");
					if(!isset($attribs['FIELDS']) || empty($attribs['FIELDS'])) 
						$attribs['FIELDS']='*';
					$fields=$this->prepareParam($attribs['FIELDS'],"attribyte  FIELDS ");

					$debuf=$this->prepareParam($attribs['DEBUG'],"attribyte  DEBUG ");
					$tail=$this->prepareParam($attribs['TAIL'],"attribyte  TAIL ");
					$tail=str_replace('&lt;','<',$tail);
					$tail=str_replace('&gt;','>',$tail);
					if ($debuf) {
						$out="<?php 	\$debugvalue=\"select $fields from $table $tail\";
								\$__rsql=base_query(\"select $fields from $table $tail\");
                                 while(\$$name=base_fetch_assoc(\$__rsql)){
                                    ?>";
					}else {
						$out="<?php  \$__rsql=base_query(\"select $fields from $table $tail\");
                                 while(\$$name=base_fetch_assoc(\$__rsql)){
                                    ?>";
					}



					$this->openLB();
					$this->out($out);


					break;  //<RBNS:foreach>

				case 'RBNS:FOR':
					// <RBNS:for name='nameindex' value='initval' expr='indexcondition_fornameindex.to right side' change='changeExpression'>
					//</RBNS:for>

					$this->checkIsAlonePresent($parser,$name);
					if(!isset($attribs['NAME']) || empty($attribs['NAME']))
						$this->errorstream('RBNS_FOR_MUST_HAVE_NAME_ATTRIB','critical',' at line'.xml_get_current_line_number($parser));
					$name=$this->prepareParam($attribs['NAME'],"attribyte  NAME ");

					if(!isset($attribs['EXPR']) || empty($attribs['EXPR']))
						$this->errorstream('RBNS_FOR_MUST_HAVE_EXPR_ATTRIB','critical',' at line'.xml_get_current_line_number($parser));
					$expr=$this->prepareParam($attribs['EXPR']," attribyte EXPR ");
					$expr=str_replace('&lt;','<',$expr);
					$expr=str_replace('&gt;','>',$expr);

					if(!isset($attribs['CHANGE']) || empty($attribs['CHANGE']))
						$this->errorstream('RBNS_FOR_MUST_HAVE_CHANGE_ATTRIB','critical',' at line'.xml_get_current_line_number($parser));
					$change=$this->prepareParam($attribs['CHANGE']," attribyte CHANGE ");

					if(!isset($attribs['VALUE']))
					$this->errorstream('RBNS_FOR_MUST_HAVE_VALUE_ATTRIB','critical',' at line'.xml_get_current_line_number($parser));
					$value=$this->prepareParam($attribs['VALUE']," attribyte VALUE ");

					$out="<?php for(\$$name=$value;\$$name$expr;\$$name$change){ ?>";


					$this->openLB();
					$this->out($out);


					break;  //<RBNS:for>


				case 'RBNS:IF':
					$this->checkIsAlonePresent($parser,$name);

					if(!is_array($this->ifpresent)) $this->ifpresent=array();
					array_push($this->ifpresent,'1');



					if( $expr=$attribs['EXPR'] )
					{

						$expr=$this->prepareParam($expr," attribyte EXPR ");

					}
					elseif( $expr=$attribs['VALUE'] )
					{
						if(preg_match('/^\w[\d\w]*$/i',$expr))
						{
							$expr='$'.$expr;
						}
						elseif(!preg_match('/^\d+$/i',$expr))
						//wrong value parametr
						die(sprintf("RBNS parse error(RBNS_IF attrib VALUE) : %s at line %d\n",
						$errorsArray[RBNS_IF_WRONG_PARAMETER],
						xml_get_current_line_number($parser)));
					}
					else
					{
						die(sprintf("RBNS parse error: %s at line %d\n",
						$errorsArray[RBNS_IF_MUST_HAVE_EXPR_ATTRIB],
						xml_get_current_line_number($parser)));
					};
					$expr=str_replace('&lt;','<',$expr);
					$expr=str_replace('&gt;','>',$expr);


					$out="<?php if($expr){ ?>";
					//echo " expr = $expr";
					$this->openLB();
					$this->out($out);

					break;

				case "RBNS:ELSEIF":
					if(count($this->ifpresent)<=0) $this->errorstream('RBNS_ELSEIF_WITHOUT_IF_BRAKES','critical',
					xml_get_current_line_number($parser));
					$this->setAloneFlag($name);
					$out="<?php }
                       else
                       { ?>";
					$this->out($out);


					break;
				case "RBNS:IMG":
					//<RBNS:img src="[ [:alpha:][:digit:]\\\/\._]" alt="[ [:alpha:][:digit:];!?,._]" height ?= ?[\'\"]([[:digit:]]+)[\'\"] width ?= ?[\'\"]([[:digit:]]+)[\'\"] maxwidth=[\'\"]([[:digit:]]+)[\'\"]  maxheight=[\'\"]([[:digit:]]+)[\'\"] />
					$getimageparamto=false;

					$this->setAloneFlag($name);

					if(!isset($attribs['SRC']) || empty($attribs['SRC'])) die(sprintf("RBNS parse error: %s at line %d\n",$this->errorstream('RBNS_IMG_MUST_HAVE_SRC_ATTRIB','return'),  	xml_get_current_line_number($parser)));
					$oldVP=$this->vparser->inExprFuncOut;
					$this->vparser->inExprFuncOut='".***."';
					$src=$this->prepareParam($attribs[SRC],'attribyte SRC ');
					$this->vparser->inExprFuncOut=$oldVP;

					foreach($attribs as $name=>$val)
					{
						switch ($name)
						{
							case 'SRC':
								break;
							case 'GETIMAGEPARAMTO': $getimageparamto=true;
							case 'ALT':
							case 'HEIGHT':
							case 'WIDTH':
							case 'MAXWIDTH':
							case 'MAXHEIGHT':
							case 'CROPIT':	

							case 'OUTERHREF':
								if(!$attribs[$name]=$this->prepareParam($attribs[$name],"attribyte '$name' ")) $attribs[$name]="''";
								break;
							default:
								$trash.=" $name='".$this->prepareParam($attribs[$name],"attribyte '$name' ")."' ";

						};
					};
					if(!$width=$attribs['WIDTH']) $width="''";
					if(!$height=$attribs['HEIGHT']) $height="''";
					if(!$alt=$attribs['ALT']) $alt="''";

					if(!$imgMaxHeight=(int)$attribs['MAXHEIGHT']) $imgMaxHeight='_RBNS_IMG_MAXHEIGHT';

					if(!$imgMaxWidth=(int)$attribs['MAXWIDTH']) $imgMaxWidth='_RBNS_IMG_MAXWIDTH';
					$cropIt=( in_array($attribs['CROPIT'],array('true','crop','tumb_and_crop')) )?$attribs['CROPIT']:"''";
					
					if($getimageparamto){ $getimageparamto="\$".$attribs['GETIMAGEPARAMTO']."=\$RBNS_img->ImageParam;";}

					if($attribs['OUTERHREF']) { $imgOuterhref='$RBNS_img->setouterhref('.$attribs['OUTERHREF'].');';};
					$out="<?php

                \$RBNS_img=new \$GLOBALS[RBNS_image_class];

				$imgOuterhref

				ob_start();
				@\$RBNS_img->show(\"".$src."\",$width,$height,$alt,\"$trash\",$imgMaxWidth,$imgMaxHeight,$cropIt);

				\$RBNS_result=ob_get_contents();
				ob_end_clean();
                $getimageparamto
				unset(\$RBNS_img);
				echo \$RBNS_result;
                ?>";
					$this->out("$out");
					break;

				case "RBNS:SETTEMPLATE":
					//<RBNS:settemplate class='RBNS_statistic' version='v2.0' method="returnShowStatistic">
					$this->checkIsAlonePresent($parser,$name);

					if(!isset($attribs['CLASS']) || empty($attribs['CLASS']))
						$this->errorstream('RBNS_SETTEMPLATE_MUST_HAVE_CLASS_ATTRIB','critical',' at line'.xml_get_current_line_number($parser));

					if(!isset($attribs['METHOD']) || empty($attribs['METHOD']))
						$this->errorstream('RBNS_SETTEMPLATE_MUST_HAVE_METHOD_ATTRIB','critical',' at line'.xml_get_current_line_number($parser));

					if(!isset($attribs['VERSION']) || empty($attribs['VERSION']))
						$version='default';
					else
						$version=$this->prepareParam($attribs['VERSION'],' attribyte VERSION ');

					$classname=$this->prepareParam($attribs['CLASS'],' attribyte CLASS ');
					$method=$this->prepareParam($attribs['METHOD'],' attribyte METHOD ');

					global $RBNS_class_templates;
					$this->openLB();
					$this->currentTemplate[$this->iLB]=&$RBNS_class_templates[$classname][$method][$version];
					$this->currentTemplateFileName[$this->iLB]=$this->makeTemplateFileName($classname,$method,$version);


					break;

				case "RBNS:FORM":
						//<form name='formname' succesmethod='method/function which run if no error here shownotsuccesonly=true submitname='submit key name' >
					
					$this->iFB++; // counter of forms emebbeding
					$FD=&$this->FormsData[$this->iFB];

					if(!isset($attribs['NAME']) || empty($attribs['NAME']))
						$this->errorstream('RBNS_FORM_MUST_HAVE_NAME_ATTRIB','critical',' at line'.xml_get_current_line_number($parser));

					$FD['NAME']=$this->prepareParam($attribs['NAME'],' attribyte NAME ',"",0);

					if(!isset($attribs['SUBMITNAME']) || empty($attribs['SUBMITNAME']))
						$this->errorstream('RBNS_FORM_MUST_HAVE_SUBMITNAME_ATTRIB','critical',' at line'.xml_get_current_line_number($parser));

					$FD['SUBMITNAME']=$this->prepareParam($attribs['SUBMITNAME'],' attribyte SUBMITNAME ');


					$FD['SUCCESMETHOD']=$this->prepareParam($attribs['SUCCESMETHOD'],' attribyte SUCCESMETHOD ');

					$FD['SHOWNOTSUCCESONLY']=$this->prepareParam($attribs['SHOWNOTSUCCESONLY'],' attribyte SHOWNOTSUCCESONLY ');

					$FD['SETVARARRAYNAME']=$this->prepareParam($attribs['SETVARARRAYNAME'],' attribyte SETVARARRAYNAME ');


					foreach($attribs as $name=>$val)
					{
						switch ($name)
						{
							case 'NAME':
							case 'SUBMITNAME':
							case 'SUCCESMETHOD':
							case 'SHOWNOTSUCCESONLY':
								break;
							default:
								$FD['TRASH'].=" $name='".$this->prepareParam($attribs[$name],"attribyte '$name' ")."' ";
						};
					};
					$out="<".$FD['NAME']."ERRORTEST><FORM NAME='".$FD['NAME']."' ".$FD['TRASH']." >";
					$this->out($out);

					break;

				case "RBNS:SELECT":

					//<RBNS:SELECT name='fieldsname' initvalue='�������� �� �����'  SETVAR='�������� ����������'  >
					$trash=''; $setvar='';
					$this->selectInitValue='';
					if(!isset($attribs['VALUE'])) $attribs['VALUE']='';
					if(!isset($attribs['NAME']) || empty($attribs['NAME']))
						$this->errorstream('RBNS_INPUT_MUST_HAVE_NAME_ATTRIB','critical',' at line'.xml_get_current_line_number($parser));
					$this->selectName=$this->prepareParam($attribs['NAME'],' attribyte NAME ');
					$selectName=$this->prepareParam($attribs['NAME'],' attribyte NAME ',"",0);

					if(!isset($attribs['INITVALUE'])) $attribs['INITVALUE']='{?'.$this->toArrayVar('initValues',$attribs['NAME']).'?}';


					$attribs['INITVALUE']=$this->prepareParam($attribs['INITVALUE'],' attribyte Value ');
					
					foreach($attribs as $name=>$val)
					{

						switch ($name)
						{
							case 'VALUE':

								break;
							case 'INITVALUE':
								$this->selectInitValue=trim($this->varparse($attribs['INITVALUE'],0));
								break;

							case 'SETVAR':
								if($setvar=$this->isValidVarsName($attribs['SETVAR']))
								{
									$FData=&$this->FormsData[$this->iFB];
									$keyPQ=($attribs['PREPAREQUEST'])?$attribs['PREPAREQUEST']:"FAH";
									$setvar="<?php
                                        if(isset(\$_REQUEST[".$FData['SUBMITNAME']."]))
                                            \$".$setvar."=prepaRequest(\$_".$this->toArrayVar("_REQUEST",$selectName).",'$keyPQ'); ?>";

								}
								else
								{
									$setvar="";
									$this->errorstream('RBNS_INPUT_WRONG_VALUE_OF_SETVAR_ATTRIB','user',' at line'.xml_get_current_line_number($parser));
								};
								break;
							case 'NAME':
								break;
							default:
								$trash.=" $name=\"".$this->prepareParam($attribs[$name],"attribyte '$name' ","",0)."\" ";
						};
					};

					$out="<SELECT NAME=\"$selectName\" $setvar  $trash >";
					$this->out($out);
					break;
				case "RBNS:OPTION":
					$trash='';
					if(!isset($attribs['VALUE']))
					$attribs['VALUE']='';
					$value=$attribs['VALUE'];
					// $value=$this->prepareParam($attribs['VALUE'],' attribyte Value ');
					if(empty($this->selectName))
					$this->errorstream('RBNS_OPTION_WITHOUT_RBNS_SELECT','user',' at line'.xml_get_current_line_number($parser));

					foreach($attribs as $name=>$val)
					{

						switch ($name)
						{
							case 'VALUE':
								
								$valout=" VALUE=\"".trim($this->varparse($value,0))."\"";
								
								$value=trim($this->varparse($value,1));

								$selectName="\$".$this->toArrayVar("_REQUEST",$this->selectName);


								if ($this->selectInitValue)
								{
												
									//set select
									$valout.=" <?php
                                           \$selectName= \"$this->selectName\";
                                        if(isset($selectName))
                                        {";

									$valout.="     if(\"$value\"==$selectName)
                                             echo \"selected\";
                                        }";
									
									if($this->vparser->isFunc($this->selectInitValue)){
										$valout.=" elseif(\"$value\"=={$this->selectInitValue}) echo \"selected\"; ?> ";
									}else{
										$valout.=" elseif(\"$value\"==\"{$this->selectInitValue}\") echo \"selected\"; ?> ";
									}
								}
								else
								{


									$valout.=" <?php

                                        if(isset($selectName))
                                           if(\"$value\"==$selectName)
                                             echo \"selected\";
                                     ?> ";
								};
								break;

							default:
								$trash.=" $name='".$this->prepareParam($attribs[$name],"attribyte '$name' ")."' ";
						};
					};
					$out="<OPTION $valout $trash >";
					$this->out($out);

					break;

					// <RBNS:FILE name='' [maxsize=] [type='image/(png|jpeg|x-png|pjpeg|jpg)'] [dir='/image'] [setvar=''] />
					//

				case "RBNS:FILE":
					
					$setvar='';
					if(!isset($attribs['NAME']) || empty($attribs['NAME']))
						$this->errorstream('RBNS_FILE_MUST_HAVE_NAME_ATTRIB','critical',' at line'.xml_get_current_line_number($parser));
					$img=$this->prepareParam($attribs['NAME'],' attribyte NAME ');


					if(!isset($attribs['TYPE'])) $ftype="";
					else     $ftype=$this->prepareParam($attribs['TYPE'],' attribyte NAME ');

					if(!isset($attribs['DIR'])) $imageDir="images";
					else     $imageDir=$this->prepareParam($attribs['DIR'],' attribyte DIR ');

					if(!isset($attribs['MAXSIZE'])) $MaxImageUploadSize=1000*1024;
					else $MaxImageUploadSize=$this->prepareParam($attribs['MAXSIZE'],' attribyte MAXSIZE ','int');

					if(isset($attribs['SAVENAME']))  $___savename____=$this->prepareParam($attribs['SAVENAME'],' attribyte SAVENAME ');


					if(isset($attribs['SETVAR'])){
						if($setvar=$this->isValidVarsName($attribs['SETVAR']))
						{
							// alone setvar
							$this->alonesetvar[$setvar]=true;
							$FData=&$this->FormsData[$this->iFB];
							// translation input data



							$setvar="
                                            if(isset(\$_REQUEST[".$FData['SUBMITNAME']."])){
                                            \$".$setvar."=\$name;

                                            };";
						}
						else{
							$setvar="";
							$this->errorstream('RBNS_INPUT_WRONG_VALUE_OF_SETVAR_ATTRIB','user',' at line'.xml_get_current_line_number($parser));
						};
					} else {
						$this->warningstream('RBNS:FILE NOT FOUND SETVAR ATTRIB');
					}

					foreach($attribs as $name=>$val)
					{

						switch ($name)
						{
							case 'SETVAR':
							case 'NAME':
							case 'PREPAREQUEST':
							case 'TYPE':
							case 'MAXSIZE':
							case 'DIR':
							case 'SAVENAME':

								break;

							default:
								$trash.=" $name='".$this->prepareParam($attribs[$name],"attribyte '$name' ")."' ";
						};
					};

					$errFormsName=$this->getFormErrorName();

					$out="<input type='file' name='$img' $trash >
                        <?php   \$ftype=\"$ftype\";
                        	if(!isset(\$__uploadedFiles)) \$__uploadedFiles=array();
                            if (\$name=&\$_FILES[$img]['name'])
                            {";
	
                   	if($___savename____){         
                   $out.="		if(method_exists(\$this,'$___savename____')) \$___savename____=\$this->$___savename____(\$name,\"$imageDir\");
                            	  elseif(function_exists('$___savename____')) \$___savename____=$___savename____(\$name,\"$imageDir\");
                        		  else \$___savename____=\"$___savename____\";
                        	 	
                            	   if(\$___savename____){
                                   	if(!strpos(\$___savename____,'.'))  \$name=\$___savename____.strstr(\$name,'.');
                                   	else \$name=\$___savename____;
                                   }";
                   	} ;              
                    $out.="

                                     \$type=\$_FILES[$img][type];
                                     \$tmp_name=\$_FILES[$img][tmp_name];
                                     \$size=\$_FILES[$img][size];
                                     if(\$ftype)
                                     	if (!ereg('^'.\$ftype.'$',\$type) || \$size==0|| \$size>$MaxImageUploadSize) \$error=true;

                                     if (!$errFormsName)
                                     {//copy file
                         				 \$name=\"/$imageDir/\$name\";
                                 	     if(copy(\$tmp_name,\$_SERVER[DOCUMENT_ROOT].\$name)) \$__uploadedFiles[]=\$_SERVER[DOCUMENT_ROOT].\$name;
                                 	     $setvar;
                                 	}
                            };
                       ?>";
					$this->out($out);

					break;

					// attribute REQUEST_CHECKED='true' (important even is mean $_REQUEST['NAME'] and insert checked
					// 
					// 
					//  translate data by default prepaRequest(,"FACH") or attribute prepaRequest
					//   by default VALUE="{?_REQUEST[$iname]?}"
					//  initvalue="{?initValues[$iname]?}"
				case "RBNS:INPUT":

					//<input name='fieldsname' initvalue='�������� �� �����'  >
					$trash=''; $setvar='';  $req_check='';
					if(!isset($attribs['NAME']) || empty($attribs['NAME'])){
						$this->errorstream('RBNS_INPUT_MUST_HAVE_NAME_ATTRIB','critical',' at line '.xml_get_current_line_number($parser));
					}
					if( (strtolower($attribs['TYPE'])=='checkbox' || strtolower($attribs['TYPE'])=='radio') 
						&& (!isset($attribs['VALUE']))){
						$this->errorstream('RBNS_INPUT_MUST_HAVE_VALUE_ATTRIB','critical',' at line '.xml_get_current_line_number($parser));
					}
					
					$iname=$this->prepareParam($attribs['NAME'],' attribyte NAME ',"",0);
					$_iname=$this->prepareParam($attribs['NAME'],' attribyte NAME ');

					
					
					
					//print_r($attribs);
					if( (strtolower($attribs['TYPE'])=='checkbox' || strtolower($attribs['TYPE'])=='radio') ){
						$value=$attribs['VALUE'];
						if(!isset($attribs['REQUEST_CHECKED'])){
							$attribs['REQUEST_CHECKED']=true;
						}
					}else{
					// value using as init value only if initvalue not present
						if(!isset($attribs['INITVALUE'])){
								$attribs['INITVALUE']=$attribs['VALUE'];
						}
						$value=$attribs['VALUE']='{?'.$this->toArrayVar('_REQUEST',$attribs['NAME']).'?}';
					}	
					// $value=$this->prepareParam($attribs['VALUE'],' attribyte Value ');
					if(!isset($attribs['INITVALUE'])) $attribs['INITVALUE']='{?'.$this->toArrayVar('initValues',$attribs['NAME']).'?}';
					$attribs['INITVALUE']=$this->prepareParam($attribs['INITVALUE'],' attribyte Value ');

					foreach($attribs as $name=>$val)
					{

						switch ($name)
						{
							case 'VALUE':
								//if (isset($attribs['INITVALUE']))
								{
									$varparse=trim($this->varparse($value,1));
									if(empty($varparse)) $varparse="''";
									$valout=" <?php
                                        if(isset(\$".$this->toArrayVar("_REQUEST",$_iname)."))";

									if( (strtolower($attribs['TYPE'])=='checkbox')&&(!$attribs['REQUEST_CHECKED'])  )
										$valout.="       echo \"VALUE='\"._prepareInputValue(".$varparse.").\"' checked \";";
									else
										$valout.="       echo \"VALUE=\\\"\"._prepareInputValue(".$varparse.").\"\\\"\";";

									$valout.=" else";
									if( (strtolower($attribs['TYPE'])=='checkbox')  )
									$valout.="    {  echo \"VALUE='\"._prepareInputValue(".$varparse.").\"'\";
                                         				if((".trim($this->varparse($attribs['INITVALUE'],0)).")==(".$varparse.")) echo 'checked'; }; ?> ";
									elseif( (strtolower($attribs['TYPE'])=='radio') )
									$valout.="    {  echo \"VALUE='\"._prepareInputValue(".$varparse.").\"'\";
                                         				if((".trim($this->varparse($attribs['INITVALUE'],0)).")==(".$varparse.")) echo 'checked'; }; ?> ";
									else
									$valout.="      echo \"VALUE=\\\"\"._prepareInputValue(".trim($this->varparse($attribs['INITVALUE'],0)).").\"\\\"\";   ?> ";
									

								};

								break;
							case 'INITVALUE':
								break;
							case 'REQUEST_CHECKED':
								$s1=strtok($_iname,"[");
								$s2=strstr($_iname,"[");
								$_selectName="\$_REQUEST[$s1]".$s2;
								if(strtolower($attribs['TYPE'])=='radio')
								$req_check="<?php if($_selectName==\"$value\") echo ' checked '; ?>";
								else $req_check="<?php if($_selectName==\"$value\") echo ' checked '; ?>";
								break;
						

							case 'SETVAR':
								if($setvar=$this->isValidVarsName($attribs['SETVAR']))
								{
									$FData=&$this->FormsData[$this->iFB];
									// data translating
									$keyPQ=($attribs['PREPAREQUEST'])?$attribs['PREPAREQUEST']:"FAH";

									$setvar="<?php
                                            if(isset(\$_REQUEST[".$FData['SUBMITNAME']."])){
                                            \$".$setvar."=prepaRequest(\$_REQUEST[".$attribs['NAME']."],'$keyPQ');

                                            } ?>";
								}
								else
								{
									$setvar="";
									$this->errorstream('RBNS_INPUT_WRONG_VALUE_OF_SETVAR_ATTRIB','user',' at line'.xml_get_current_line_number($parser));
								};
								break;
							case 'NAME':
								break;
							default:
								$trash.=" $name=\"".$this->prepareParam($attribs[$name],"attribyte '$name' ","",0)."\" ";
								//$trash.=" $name=\"".$this->prepareParam($attribs[$name],"attribyte '$name' ")."\" ";
						};
					};
					$out="<INPUT NAME='$iname' $valout $setvar $req_check $req_value $trash >";
					$this->out($out);
					break;


				case "RBNS:TEXTAREA":

					//<textarea name='fieldsname' initvalue='�������� �� �����' [setvar='nameofvar']  >value</textarea>
					$trash=''; $setvar='';

					if($this->inTextArea) // can't be embbeded -die
					$this->errorstream('RBNS_TEXTAREA_MUST_NOT_NESTED','critical',' at line'.xml_get_current_line_number($parser));
					$this->inTextArea=1;

					if(empty($attribs['NAME']))
					$this->errorstream('RBNS_TEXTAREA_MUST_HAVE_NAME_ATTRIB','critical',' at line'.xml_get_current_line_number($parser));

					$this->TextAreaName=$this->prepareParam($attribs['NAME'],' attribyte NAME ',"",1);
					$iname=$this->prepareParam($attribs['NAME'],' attribyte NAME ',"",0);
					
					
					
					if(!isset($attribs['INITVALUE'])) $attribs['INITVALUE']='{?'.$this->toArrayVar('initValues',$attribs['NAME']).'?}';

					$this->TextAreaInitValue=$attribs['INITVALUE']=$this->prepareParam($attribs['INITVALUE'],' attribyte Value ');
					
					
					
					
					foreach($attribs as $name=>$val)
					{

						switch ($name)
						{

							case 'INITVALUE':
								break;

							case 'SETVAR':
								if($setvar=$this->isValidVarsName($attribs['SETVAR']))
								{
									$FData=&$this->FormsData[$this->iFB];
									$keyPQ=($attribs['PREPAREQUEST'])?$attribs['PREPAREQUEST']:"FAH";

									$setvar="<?php
                                        if(isset(\$_REQUEST[".$FData['SUBMITNAME']."]))
                                            \$".$setvar."=prepaRequest(\$_REQUEST[".$attribs['NAME']."],'$keyPQ'); ?>";
								}
								else
								{
									$setvar="";
									$this->errorstream('RBNS_INPUT_WRONG_VALUE_OF_SETVAR_ATTRIB','user',' at line'.xml_get_current_line_number($parser));
								};
								break;
							case 'PLUGIN':
							case 'NAME':
								break;
								
							default:
								$trash.=" $name='".$this->prepareParam($attribs[$name],"attribyte '$name' ","",0)."' ";
						};
					};
					// for WYSIWYG
					$plugin="";
					$this->TEXTAREAplugined=false;
					if(isset($attribs['PLUGIN'])){
						$pluginName=$attribs['PLUGIN'];
						$plugin="<?php if(method_exists(\$this,'".$pluginName."'))
                                       \$__plugin4$this->TextAreaName=\$this->$pluginName(\"{$this->TextAreaName}\",\"".trim($this->varparse($this->TextAreaInitValue,0))."\",\"".addslashes($trash)."\");
                                  else
                                       \$__plugin4$this->TextAreaName=\$funame(\"{$this->TextAreaName}\",\"".trim($this->varparse($this->TextAreaInitValue,0))."\",\"".addslashes($trash)."\"); ?>";
                        unset($pluginName);                
					}
					
					
					if($plugin) {
						$this->TEXTAREAplugined=true;
						$out="$plugin; <?php if(\$__plugin4$this->TextAreaName){ ?> <TEXTAREA NAME='$iname' $setvar  $trash > <?php } ?>";
					}else{
						$out="<TEXTAREA NAME='$iname' $setvar  $trash >";
					}	
					$this->out($out);
					$this->openLB();

					break;
				 
				case "RBNS:TRD_SUBMITNAME":
                	if(!isset($attribs['VALUE']) || empty($attribs['VALUE']))
                                $this->errorstream('TRD_SUBMITNAME_HAVE_VALUE_ATTRIB','critical',' at line'.xml_get_current_line_number($parser));
                	$value=$this->prepareParam($attribs['VALUE'],' TRD_SUBMITNAME attribyte VALUE ');
             	
                	$this->iFB++; //
                	$FD=&$this->FormsData[$this->iFB];
                	$FD['SUBMITNAME']=$this->prepareParam($value,' attribyte SUBMITNAME ');
					
                 break;			

				case "RBNS:ERROR":
					//<error name='fieldsname' check='method/func for check data' [param="'param1',param2"] ifsetonly='true' [setvar='nameofvar']  [preset=function1[|function2]]  text='error message'>
					// checking $_REQUEST[fieldsname]
					// output divide for  2 way chekin and show error message
					// checking working before form 
					// if ifsetonly attribute present checking will run if var is not ''
					//[preset=function1[|function2]]
					//param="'param1',param2" (checkparam)- that attribute send additional parameters to function check,
					//First parameter always is $_REQUEST[fieldsname]

					//RBNS 0.3  :  setvar="this::data[$name] by default

					$setvar="";
					if(!isset($attribs['NAME']) || empty($attribs['NAME']))
						$this->errorstream('RBNS_ERROR_MUST_HAVE_NAME_ATTRIB','critical',' at line'.xml_get_current_line_number($parser));
					$name=$this->prepareParam($attribs['NAME'],' RBNS_ERROR attribyte NAME ');

					if(!isset($attribs['SETVAR'])){
						$FD=&$this->FormsData[$this->iFB];
						if ($FD['SETVARARRAYNAME'] ) {
							$attribs['SETVAR']= $this->toArrayVar($FD['SETVARARRAYNAME'],$attribs['NAME']);
						}else{
							$attribs['SETVAR']=$this->toArrayVar("this::data",$attribs['NAME']);
						}
					}

					if(!isset($attribs['CHECK']) || empty($attribs['CHECK']))
						$this->errorstream('RBNS_ERROR_MUST_HAVE_CHECK_ATTRIB','critical',' at line'.xml_get_current_line_number($parser));
					$check=$this->prepareParam($attribs['CHECK'],' RBNS_ERROR attribyte CHECK ');

					if(!empty($attribs['SETCHECKFUNC']))
					$checkfunction=$this->prepareParam($attribs['SETCHECKFUNC'],' RBNS_ERROR attribyte SETCHECKFUNC ');
					else $checkfunction='empty';

					if(!isset($attribs['TEXT']) || empty($attribs['TEXT']))
					$attribs['TEXT']='';
					$text=$this->prepareParam($attribs['TEXT'],' RBNS_ERROR attribyte TEXT ');
					$param =$this->prepareParam($attribs['PARAM'],"attribyte  PARAM ");

					$varname='';

					if($attribs['SETVAR'] && $this->alonesetvar[$varname=$this->isValidVarsName($this->prepareParam($attribs['SETVAR'],"attribyte  SETVAR"))]!==true )
					{


						if($varname)
						{

							$keyPQ=($attribs['PREPAREQUEST'])?$attribs['PREPAREQUEST']:"FAH";
							$setvar="  \$".$varname."=prepaRequest(\$".$this->toArrayVar("_REQUEST",$name).",'$keyPQ');
                                    \$".$this->toArrayVar("_REQUEST",$name)."=prepaRequest(\$".$this->toArrayVar("_REQUEST",$this->varparse($attribs['NAME'],1)).",'$keyPQ'); ";

						}
						else
						{
							$setvar="";
							$this->errorstream('RBNS_ERROR_WRONG_VALUE_OF_SETVAR_ATTRIB','critical',' at line'.xml_get_current_line_number($parser));
						};


						if($attribs['PRESET'])
						{

							if(!$varname)  $this->errorstream('RBNS_ERROR_WRONG_VALUE_OF_SETVAR_ATTRIB','critical',' at line'.xml_get_current_line_number($parser));
							if(!$attribs['SETVAR']) $this->errorstream('RBNS_ERROR_ATTRIB_PRESET_USED_WITHOUT_SETVAR','user',' at line'.xml_get_current_line_number($parser));
							else
							{

								$func=explode('|',$attribs['PRESET']);
								//print_r($func);
								foreach($func as $funame)
								{
									if(trim($funame))
									$setvar.="
                                  if(method_exists(\$this,'".$funame."'))
                                        \$$varname=\$this->$funame(\$$varname);
                                  else
                                        \$$varname=$funame(\$$varname);
                                          ";
								};
							};
						};
					};
					
					$formname=$this->FormsData[$this->iFB]['NAME'];
					$errFormsName=$this->getFormErrorName();
					
					if(!isset($this->numErr[$name])) $this->numErr[$name]=0;

					$errVarName="\$". $this->toArrayVar("_RT_er_",$name)."[".$this->numErr[$name]."]";
					$errVarsName="\$". $this->toArrayVar("_RT_error_",$name);
					
					$checkpart="

                     if(method_exists(\$this,'".$check."'))
                          $errVarName=!\$this->$check(\$".$this->toArrayVar("_REQUEST",$name).(($param)?(",$param"):"").");
                     else
                          $errVarName=!$check(\$".$this->toArrayVar("_REQUEST",$name).(($param)?(",$param"):"").");
                     if($errVarName){
                     		$errVarsName=true;
                     		$errFormsName=true;
                     } 
                    
                    ";

					if($attribs['IFSETONLY']) $checkpart="if(!$checkfunction(\$".$this->toArrayVar("_REQUEST",$name).(($checkfunction!='empty')?",'$name'":"").")){ ".$checkpart." };";

					if($setvar)
					{
						$FData=&$this->FormsData[$this->iFB];
						$out="<?php

                                if(isset(\$_REQUEST[".$FData['SUBMITNAME']."]))
                                {
                                    if(!($errVarName)){ $setvar }
                                    else {
                                        \$errorof$formname=true;
                                         echo '$text';

                           ?>";
					}
					else
					$out="<? if($errVarName){ \$errorof$formname=true; ".(($text)?"echo $text;":"")."{ ?> ";
					$this->numErr[$name]++;

					$this->FormsData[$this->iFB]['ERRORTEST'].=$checkpart;
					$this->out($out);
					break;


				default:



			}
		}
		else
		print "&lt;<font color=\"#0000cc\">$name</font>";

	}

	function endElement($parser, $name) {

		if(substr(strtoupper($name),0,4)=='RBNS')
		{

			switch ($name)
			{
				case 'RBNS:OBJECT':
				case 'RBNS:FANTOM':
				case 'RBNS:IMG':
				case 'RBNS:FUNCTION':
				case 'RBNS:SET':
				case 'RBNS:ELSEIF':
				case "RBNS:FILE":
				case "RBNS:TRD_SUBMITNAME":	
					$this->clearAloneFlag();
					break;
				case 'RBNS:SELECT':
					$this->selectName='';
					$this->out("</SELECT>");
					break;
				case 'RBNS:COMMENT':
					$out="<?php */ echo '-->';  ?>";
					$this->out("$out");
					break;
				case 'RBNS:FOREACH':
				case 'RBNS:SQLEACH':
				case 'RBNS:FOR':
				case 'RBNS:DATA':
					
					$this->closeLB();
					$this->out("<?php \$this->runAspect('DATA','end');}; \$this->runAspect('DATA','after');?>");

					break;
				case 'RBNS:FETTERS':

					$out="<?php \$RBNS_fantoms[".$this->shackleName."]=ob_get_contents();
           				ob_end_clean(); ?>";
					$this->out($out);
					$this->shackle=false;


					break;
				case 'RBNS:IF':

					array_pop($this->ifpresent);
					$this->closeLB();
					$this->out("<?php };?>");

					break;

				case "RBNS:SETTEMPLATE":
					$this->parse_result=$this->varparse($this->parse_result,$this->defvarout);
					$this->parse_result=preg_replace('/\?>\s*<\?php/mi','',$this->parse_result);
					
					if(defined('RBNS_XML_ENCODE')){
						$this->parse_result=iconv('UTF-8',RBNS_XML_ENCODE,$this->parse_result);
					}
					
					$this->currentTemplate[$this->iLB]=$this->parse_result;

					$fname=$this->currentTemplateFileName[$this->iLB];

					if(!$fn=fopen($fname,'w'))  die("File $fname is not exists!");
					fwrite($fn,$this->parse_result);
					fclose($fn);

					if(!create_function("","?>$this->parse_result<?")){ 
						$fn=$_SERVER["DOCUMENT_ROOT"]."/temp/last_wrong_parse.php";
						$this->parse_warning(" <font color=red> ".$this->iLB." RBNS:SETTEMPLATE for file $fname is not valid php-program!</font>",2);
						$this->parse_warning(" <font color=red> saved in $fn</font>",2);
						file_put_contents($fn,$this->parse_result);
					}	
					else $this->parse_warning(" <font color=green> ".$this->iLB." RBNS:SETTEMPLATE for file $fname is  php-program!</font>",2);

					$this->parse_result='';
					$this->closeLB();

					break;

				case "RBNS:TEXTAREA":
					$this->inTextArea=0;

					$value=$this->parse_result;
					$s=trim($this->varparse($value,1));

					if ($this->TextAreaInitValue)
					{
						$valout="<?php
			                 if(isset(\$_REQUEST[".$this->TextAreaName."]))	echo \$_REQUEST[".$this->TextAreaName."];
			                       
			                 else ";
			                 if($s){ $valout.=" echo \"$s\";";}
			                 else{
			                 	$valout.="  echo \"".trim($this->varparse($this->TextAreaInitValue,0))."\";";
							  }	
			                 $valout.=" ?>";
					}
					else{
						$valout=trim($this->varparse($value,0));
					}				
					$valout=preg_replace('/\?>\s*<\?php/mi','',$valout);

					$this->parse_result='';

					$this->closeLB();
					if($this->TEXTAREAplugined){
						$this->out("
						<?php if(\$__plugin4$this->TextAreaName){ ?>{$valout}</TEXTAREA><?php } ?>
								");
						
					}else{
						$this->out("$valout</TEXTAREA>");
					}

					break;
				case "RBNS:FORM":
					//<FORM NAME='FORMNAME' SUCCESMETHOD='' SHOWNOTSUCCESONLY=TRUE SUBMITNAME='��� C�����' >

					$FD=&$this->FormsData[$this->iFB];

					$checkpart="<?php
                 if(isset(\$_REQUEST[".$FD['SUBMITNAME']."]))
                 {
                    ".$FD['ERRORTEST']."
                 };
                ?>";
					$formname=$FD['NAME'];
					if($FD['SHOWNOTSUCCESONLY'])
					$checkpart.="<?php
                            if(isset(\$_REQUEST[".$FD['SUBMITNAME']."])&&empty(\$errorof$formname))
                            {
                             ob_start();
                            }; ?>";

					$this->replaceInResult("<".$FD['NAME']."ERRORTEST>",$checkpart);


					if($FD['SUCCESMETHOD'])
					{
						$sc=$FD['SUCCESMETHOD']; $pr='';
						//checking params 
						if(ereg('(.*)\((.*)\)',$sc,$reg))
						{
							$sc=$reg[1]; $pr=$reg[2];
						};

						$succes="
                     \$__suc='".$sc."';


                    if(function_exists(\$__suc))
                           \$__suc($pr);
                    elseif(method_exists(\$this,\$__suc))
                           \$this->\$__suc($pr);
                    else
                           echo \"\$__suc\";
                    ";
					};
					
					$clear='
					if(is_array($__uploadedFiles))
					for($i=0;$i<count($__uploadedFiles);$i++){
						unlink($__uploadedFiles[$i]);
					}';

					
					if($FD['SHOWNOTSUCCESONLY'])
					{


						$out="</FORM><?php

                            if(isset(\$_REQUEST[".$FD['SUBMITNAME']."])&&empty(\$errorof$formname))
                            {
                             ob_end_clean();
                             $succes;
                            }else {
                           	 $clear
						    };?> ";
					}
					elseif($FD['SUCCESMETHOD'])
					$out="<?php
                           if(isset(\$_REQUEST[".$FD['SUBMITNAME']."])&&empty(\$errorof$formname))
                           {
                             $succes;
                           }else {
                           	 $clear
						   };
                            ?> </FORM>";
					else{
						$out=" </FORM>";
					}	

					$this->out($out);
					unset($this->FormsData[$this->iFB]);
					$this->iFB--; 

					break;


				case "RBNS:OPTION":
					$this->out("</OPTION>");
					break;

				case "RBNS:ERROR":
					$this->out(" <?php }; }; ?> ");
					break;
				case "RBNS:SETTEMPLATE":
				case "RBNS:INPUT":

					break;
				default:




			}
		}



	}

	function characterData($parser, $data) {
		//if(trim($data))
		$this->checkIsAlonePresent($parser,$data);

		$this->out("$data");
	}



	function defaultHandler($parser, $data) {

	}




	function varparse($data,$inExpr=0){
		global $errorsArray;
		if($inExpr) $this->vparser->setInExpr();
		else        $this->vparser->clearInExpr();

		
		$data=$this->vparser->parse($data);
		
			
		return $data;

	}

	function makeObjectSyntax($str){
		return $str=ereg_replace('^([[:alpha:]_][[:alpha:][:alnum:]_]*)::([[:alpha:]_][[:alpha:][:alnum:]_]*)','\\1->\\2',$str);

	}
	function isValidVarsName($str){

		$str=$this->makeObjectSyntax($str);
		//echo "str=<font color=brown>$str</font><br>";
		if ( (ereg('[[:alpha:]_][[:alpha:][:alnum:]_]*',$str))||(ereg('[[:alpha:]_][[:alpha:][:alnum:]_]*->[[:alpha:]_][[:alpha:][:alnum:]_]*',$str)) )
		return $str;
		else  return false;
	}

};//object
?>